<?php

require_once 'logging.php';

global $log;

if(!defined("DEBUG_MODE")) {
   define("DEBUG_MODE", "DEBUG");
}

set_error_handler("errorHandler", E_ALL);

register_shutdown_function(function () {
            global $log;
            if ($e = error_get_last()) {
                $log->error($e['message'] . " in " . $e['file'] . ' line ' . $e['line']);
            }
        });

class PHPResult {

    public $resultado = false;
    public $esError = false;
    public $mensaje = "Error no definido";

    public function __construct($resultado = false, $esError = false, $mensaje = "Error no definido") {
        $this->resultado = $resultado;
        $this->esError = $esError;
        $this->mensaje = $mensaje;
    }

    public function __toString() {
        if ($this->esError) {
            return "Se ha producido el siguiente error: {$this->message}.";
        } else {
            return "{$this->message} (El resultado de la acción ha sido: {$this->resultado})";
        }
    }

}

class DAWPCError extends Exception {

    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null) {
        // some code
        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return "Se ha producido el siguiente error: {$this->message}.";
    }

}

class SQLError extends DAWPCError {

    public $sql;
    public $sqlError;

    // Redefine the exception so message isn't optional
    public function __construct($message, $sqlError, $sql, $code = 0, Exception $previous = null) {
        // some code
        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
        $this->sql = $sql;
        $this->sqlError = $sqlError;
    }

    // custom string representation of object
    public function __toString() {
        return "{$this->message}.<br>Se ha producido el siguiente error: {$this->sqlError}.<br/>Al ejecutar la consulta {$this->sql}.";
    }

}

function check_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function errorHandler($errno, $errstr) {
    $error = new PHPResult();
    $error->resultado = false;
    $error->esError = true;
    $error->mensaje = "Se ha producido el siguiente error $errstr($errno)";
    exit(json_encode($error));
}
?>

